package com.zzty.zzlp.controller;

import com.zzty.zzlp.commom.FileUpload;
import com.zzty.zzlp.entity.User;
import com.zzty.zzlp.service.QuestionService;
import com.zzty.zzlp.service.TeamExamService;
import com.zzty.zzlp.service.TeamExamTransationService;
import com.zzty.zzlp.service.UserService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/TeamExam")
public class TeamExamController {

    @Autowired
    TeamExamService tes;

    @Autowired
    TeamExamTransationService tets;

    @Autowired
    UserService us;

    @Autowired
    QuestionService qs;

    @RequestMapping(value = "/judgeStart", produces = {"text/html;charset=UTF-8;"})
    @ResponseBody
    public String judgeStart(HttpServletRequest request) {

        User user = (User) request.getSession().getAttribute("User");
//        User user = new User();
//        user.setName("ssc");
//        user.setClazzId(4);
//        user.setId(63);
        Integer clazzId = user.getClazzId();
        String name = user.getName();
        Integer examId = searchExamId(name);
        System.out.println("examId= " + examId);
        Integer userId = user.getId();
        String userIds = tets.searchUserids(examId, userId);
        if (examId == null) {
            return ("无法开始");
        } else {
            String result = "";
            JSONObject json = new JSONObject();
            if (isTimeToStart()) {
                String state = tets.searchStateToStartTime(examId, userIds, userId);
                result = tets.searchState(examId, userIds);
                if ("请_等_待".equals(state)) {
                    String waits[] = state.split("_");
                    String wait = waits[0] + waits[1] + waits[2] + "你的队友";
                    json.put("question", wait);
                    System.out.println("userids:" + userIds);
                    String seachId[] = userIds.split("\\|");
                    String suserid = userId + "";
                    int teamerId = 0;
                    for (int i = 0; i < seachId.length; i++) {
                        if (!suserid.equals(seachId[i])) {
                            String steamerId = seachId[i];
                            System.out.println("steamerId:" + steamerId);
                            teamerId = Integer.parseInt(steamerId);
                        }
                    }
                    try {
                        User tmpUser = new User();
                        tmpUser.setId(teamerId);
                        User u1 = us.selectUserById(teamerId);
                        System.out.println(u1.toString());
                        String stuName = u1.getDisname();
                        System.out.println("队友"+ stuName);
                        json.put("teamerId", stuName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
//                    Integer leftTime = leftTime(examId, userIds);
//                    json.put("leftTime", leftTime);
//                    System.out.println(leftTime);
                    System.out.println(json.toString());
                    return (json.toString());
                } else {
                    Integer leftTime = leftTime(examId, userIds);
                    json.put("leftTime", leftTime);
                    String seachId[] = userIds.split("\\|");

                    String suserid = userId + "";
                    int teamerId = 0;
                    for (int i = 0; i < seachId.length; i++) {
                        if (!suserid.equals(seachId[i])) {
                            String steamerId = seachId[i];
                            teamerId = Integer.parseInt(steamerId);
                        }
                    }
                    if (teamerId != 0) {
                        try {
                            User tmpUser = new User();
                            tmpUser.setId(teamerId);
                            User u1 = us.selectUserById(teamerId);
                            String stuName = u1.getDisname();
                            System.out.println(u1.toString());
                            System.out.println("队友"+ stuName);
                            json.put("teamerId", stuName);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        String stuName = "没有(靠自己吧)";
                        System.out.println("队友"+ stuName);
                        json.put("teamerId", stuName);
                    }
                    Calendar c = Calendar.getInstance();
                    String date = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-"
                            + c.get(Calendar.DAY_OF_MONTH);
                    String questions[] = getQuestionID(date, clazzId);
                    String question = getQuestion(questions);
                    System.out.println("question:" + question);
                    json.put("question", question);

                    System.out.println(json.toString());
                    return (json.toString());
                }
            } else {
                return ("无法开始");
            }
        }
    }

    @RequestMapping("/uploadFile")
    public void uploadFile(HttpServletRequest request, @RequestParam("teamfileName") MultipartFile file, HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("User");
//        User user = new User();
//        user.setName("ssc");
//        user.setId(63);
        String name = user.getName();
        Integer examId = searchExamId(name);
        Integer userId = user.getId();
        String userIds = tets.searchUserids(examId, userId);
        if (tets.judgeTotalTime(examId, userIds)) {
//            return ("fail");
            response.sendRedirect("../html/main.html#!/zzty");
        } else {
            updateTotalTime(examId, userIds);
            System.out.println(file.getOriginalFilename());
            upLoad(file, examId, userIds);
//            return ("Success");
            response.sendRedirect("../html/main.html#!/zzty");
        }
    }

    @RequestMapping("/teamExamPage")
    public String toTeamExamPage() {
        return "TeamExam";
    }

    protected Integer searchExamId(String name) {
        Integer clazzId = tes.searchClazzId(name);
        Calendar c = Calendar.getInstance();
        String date = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH);
        Integer examId = tes.searchExamId(date, clazzId);
        return examId;
    }

    protected boolean isTimeToStart() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("HH");
        int hour = Integer.parseInt(sdf.format(date));
        if (hour >= 10 && hour < 24) {
            return true;
        } else {
            return false;
        }
    }

    protected Integer leftTime(int examId, String userIds) {

        Integer leftseconds = tets.leftTime(examId, userIds);
        return leftseconds;
    }

    protected String[] getQuestionID(String date, Integer clazzId) {
        String[] qusetions = tes.getQuestionID(date, clazzId);
        return qusetions;
    }

    protected void updateTotalTime(Integer examId, String userIds) {
        tets.updateTotalTime(examId, userIds);
        tets.judgeIsValid(examId, userIds);
    }

    protected void upLoad(MultipartFile file, Integer examId, String userIds) throws Exception {
        System.out.println("upload");
        try {
            Map<String, String> fileInfo = FileUpload.uploadFile(file, "teamExam");
            String answers = fileInfo.get("filename");
            System.out.println("-------------" + answers);
            tets.updateAnswer(examId, userIds, answers);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getQuestion(String[] array) {
        String questions = "";
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
            String tmpContent = "";
            if (qs.selectQuecontent(array[i] + "") == null) {
                tmpContent = "题目不存在";
            } else {
                tmpContent = qs.selectQuecontent(array[i] + "").getContent();
            }
            questions = questions + (i + 1) + "." + tmpContent + "\r\n";
        }
        return questions;
    }


    @RequestMapping(value = "/uploadFile1", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject uploadFile1(@RequestParam(value = "files") MultipartFile files, HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("User");
//        User user = new User();
//        user.setName("ssc");
//        user.setId(63);
        String name = user.getName();
        Integer examId = searchExamId(name);
        Integer userId = user.getId();
        String userIds = tets.searchUserids(examId, userId);
        JSONObject jb = new JSONObject();
        if (tets.judgeTotalTime(examId, userIds)) {
            System.out.println("fail");
            // response.sendRedirect("../html/main.html#!/zzty");
            jb.put("massage", "fail");
            return jb;

        } else {
            updateTotalTime(examId, userIds);
            System.out.println(files.getOriginalFilename());
            upLoad(files, examId, userIds);
            System.out.println("success");
            // response.sendRedirect("../html/main.html#!/zzty");
            jb.put("massage", "success");
            return jb;
        }

    }

    @RequestMapping(value = "/identity", method = RequestMethod.GET)
    @ResponseBody
    public int uploadFile1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("User");
        return user.getType();
    }

}
